package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    @Autowired
    ThirdPartService thirdPartService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    Integer smsCodeTime = 100;  //验证码发送时间间隔

    @PostMapping("/login")
    public R login(@RequestBody UserLoginVo vo){
        R login = memberFeignService.login(vo);
        if(login.getCode() == 0){
            return R.ok();

        }
        return R.error(BizCodeEnume.LOGIN_FAILD);
    }

    @PostMapping("/reg")
    public R register(@Valid UserRegisterVo vo, BindingResult result){
        if(result.hasErrors()){
//            List<FieldError> fieldErrors = result.getFieldErrors();
//            fieldErrors.get(0).getField();
//            fieldErrors.get(0).getDefaultMessage();
            return R.error().put("error",result);
        }else{
//            校验验证码
            String redisCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_PREFIX + vo.getPhone());
            if(redisCode!=null){
                String[] s = redisCode.split("_");
                if(vo.getCode().equalsIgnoreCase(s[0])){
                    redisTemplate.delete(AuthConstant.SMS_CODE_PREFIX + vo.getPhone());
//                    远程调用注册服务
                    R r = memberFeignService.register(vo);
                    if(r.getCode() == 0){
//                        成功
                        return R.ok();
                    }else{
                        String msg = r.getData(new TypeReference<String>() {
                        });
                        return R.error().put("msg",msg);
                    }
                }else{
                    return R.error(BizCodeEnume.AUTH_CODE_ERROR);
                }
            }else{
                return R.error(BizCodeEnume.AUTH_CODE_EXPIRED);
            }
        }
    }

    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
//        1.防止重复刷验证码
        String redisCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_PREFIX + phone);
        if(redisCode!=null){
            long sendTime = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis() - sendTime < smsCodeTime * 1000){
                return R.error(BizCodeEnume.SMS_HIGH_FREQUENCY);
            }
        }

//        2.验证码暂存/过期  存code_phone  code
        String code = UUID.randomUUID().toString().substring(0, 5);
        long time = System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthConstant.SMS_CODE_PREFIX+phone,code+"_"+time,60, TimeUnit.SECONDS);

//        发送验证码
        thirdPartService.sendMsg(phone,code);
        System.out.println("验证码 : "+code);
        return R.ok();
    }
}
